<template>
    <div class="homepage-container">
      <!-- 概览卡片区 -->
      <div class="overview-section">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6">
            <el-card class="stat-card" shadow="hover">
              <div class="card-content">
                <div class="icon-container bg-blue">
                  <el-icon><Wallet /></el-icon>
                </div>
                <div class="card-info">
                  <div class="card-title">账户余额</div>
                  <div class="card-value">¥{{ formatCurrency(stats.balance) }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-card class="stat-card" shadow="hover">
              <div class="card-content">
                <div class="icon-container bg-green">
                  <el-icon><TrendCharts /></el-icon>
                </div>
                <div class="card-info">
                  <div class="card-title">本月收入</div>
                  <div class="card-value">¥{{ formatCurrency(stats.monthlyIncome) }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-card class="stat-card" shadow="hover">
              <div class="card-content">
                <div class="icon-container bg-orange">
                  <el-icon><ShoppingCart /></el-icon>
                </div>
                <div class="card-info">
                  <div class="card-title">待处理交易</div>
                  <div class="card-value">{{ stats.pendingTransactions }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-card class="stat-card" shadow="hover">
              <div class="card-content">
                <div class="icon-container bg-purple">
                  <el-icon><User /></el-icon>
                </div>
                <div class="card-info">
                  <div class="card-title">活跃客户</div>
                  <div class="card-value">{{ stats.activeCustomers }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
  
      <!-- 功能区 -->
      <div class="action-section">
        <el-row :gutter="20">
          <el-col :xs="24" :md="16">
            <el-card shadow="never" class="action-card">
              <template #header>
                <div class="card-header">
                  <h3>快捷操作</h3>
                </div>
              </template>
              <div class="quick-actions">
                <el-button type="primary" class="action-button" @click="openPaymentDialog">
                  <el-icon><Money /></el-icon>
                  <span>发起付款</span>
                </el-button>
                <el-button type="success" class="action-button" @click="navigateToBilling">
                  <el-icon><Collection /></el-icon>
                  <span>创建账单</span>
                </el-button>
                <el-button type="warning" class="action-button">
                  <el-icon><CreditCard /></el-icon>
                  <span>充值账户</span>
                </el-button>
                <el-button type="info" class="action-button">
                  <el-icon><Download /></el-icon>
                  <span>导出报表</span>
                </el-button>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :md="8">
            <el-card shadow="never" class="action-card">
              <template #header>
                <div class="card-header">
                  <h3>账户安全</h3>
                </div>
              </template>
              <div class="security-status">
                <el-steps direction="vertical" :active="2">
                  <el-step title="登录验证" description="已开启双重验证" />
                  <el-step title="支付密码" description="已设置" />
                  <el-step title="API密钥" description="未配置" />
                </el-steps>
                <el-button type="primary" plain size="small" class="security-button">
                  安全设置
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
  
      <!-- 交易记录 -->
      <div class="transaction-section">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <h3>最近交易记录</h3>
              <div>
                <el-button text @click="navigateToTransactions">查看全部</el-button>
              </div>
            </div>
          </template>
          <el-table :data="recentTransactions" style="width: 100%">
            <el-table-column prop="id" label="交易号" width="140" />
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="recipient" label="收款方" />
            <el-table-column prop="amount" label="金额" align="right" width="140">
              <template #default="{ row }">
                <span :class="row.type === 'income' ? 'income-amount' : 'outcome-amount'">
                  {{ row.type === 'income' ? '+' : '-' }}¥{{ formatCurrency(row.amount) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)" size="small">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default>
                <el-button size="small">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
  
      <!-- 图表区 -->
      <div class="chart-section">
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-card shadow="never">
              <template #header>
                <div class="card-header">
                  <h3>收入分析</h3>
                </div>
              </template>
              <div class="chart-container">
                <div ref="incomeChart" style="height: 300px;"></div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-card shadow="never">
              <template #header>
                <div class="card-header">
                  <h3>交易类型分布</h3>
                </div>
              </template>
              <div class="chart-container">
                <div ref="typeChart" style="height: 300px;"></div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
  
      <!-- 发起付款对话框 -->
      <el-dialog v-model="paymentDialogVisible" title="发起付款" width="500px">
        <el-form :model="paymentForm" label-width="80px">
          <el-form-item label="收款方">
            <el-select v-model="paymentForm.recipient" placeholder="请选择或输入收款方">
              <el-option label="腾讯云服务" value="1" />
              <el-option label="阿里云服务" value="2" />
              <el-option label="服务器托管商" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="金额">
            <el-input v-model="paymentForm.amount" placeholder="请输入金额">
              <template #prepend>¥</template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="paymentForm.note"
              type="textarea"
              placeholder="请输入付款备注"
              :rows="3"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="paymentDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitPayment">确认支付</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, reactive, onMounted, onUnmounted , computed} from 'vue'
  import { useRouter } from 'vue-router'
  import { useAppStore } from '../store'
  import * as echarts from 'echarts'
  import {
    Wallet,
    TrendCharts,
    ShoppingCart,
    User,
    Money,
    Collection,
    CreditCard,
    Download
  } from '@element-plus/icons-vue'
  
  const router = useRouter()
  const store = useAppStore()
  
  const stats = computed(() => store.stats)
  
  // 交易记录数据
  const recentTransactions = ref([
    { id: 'TX20230714001', date: '2023-07-14', recipient: '腾讯云服务', amount: 1250.00, type: 'outcome', status: '已完成' },
    { id: 'TX20230713002', date: '2023-07-13', recipient: '客户A公司', amount: 8500.00, type: 'income', status: '已完成' },
    { id: 'TX20230712003', date: '2023-07-12', recipient: '阿里云服务', amount: 3200.00, type: 'outcome', status: '处理中' },
    { id: 'TX20230711004', date: '2023-07-11', recipient: '客户B公司', amount: 5600.00, type: 'income', status: '已完成' },
    { id: 'TX20230710005', date: '2023-07-10', recipient: '服务器托管', amount: 1800.00, type: 'outcome', status: '已完成' }
  ])
  
  // 付款对话框
  const paymentDialogVisible = ref(false)
  const paymentForm = reactive({
    recipient: '',
    amount: '',
    note: ''
  })
  
  // 图表实例
  let incomeChart: echarts.ECharts | null = null
  let typeChart: echarts.ECharts | null = null
  const incomeChartRef = ref<HTMLElement | null>(null)
  const typeChartRef = ref<HTMLElement | null>(null)
  
  // 初始化图表
  const initCharts = () => {
    if (incomeChartRef.value) {
      incomeChart = echarts.init(incomeChartRef.value)
      const incomeOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月'],
          axisLine: {
            lineStyle: {
              color: '#dcdfe6'
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: true,
            lineStyle: {
              color: '#dcdfe6'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f5f7fa'
            }
          }
        },
        series: [
          {
            name: '收入',
            type: 'bar',
            data: [12500, 18200, 19100, 23400, 29000, 33000, 32850],
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            }
          }
        ]
      }
      incomeChart.setOption(incomeOption)
    }
  
    if (typeChartRef.value) {
      typeChart = echarts.init(typeChartRef.value)
      const typeOption = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center'
        },
        series: [
          {
            name: '交易类型',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 1048, name: '线上支付' },
              { value: 735, name: '银行转账' },
              { value: 580, name: '扫码支付' },
              { value: 484, name: 'API支付' },
              { value: 300, name: '其他' }
            ]
          }
        ]
      }
      typeChart.setOption(typeOption)
    }
  }
  
  // 打开付款对话框
  const openPaymentDialog = () => {
    paymentDialogVisible.value = true
  }
  
  // 提交付款
  const submitPayment = () => {
    // 这里应该是实际的支付API调用
    console.log('提交付款:', paymentForm)
    paymentDialogVisible.value = false
    // 重置表单
    paymentForm.recipient = ''
    paymentForm.amount = ''
    paymentForm.note = ''
    
    // 模拟添加交易记录
    recentTransactions.value.unshift({
      id: `TX${new Date().getTime()}`,
      date: new Date().toISOString().split('T')[0],
      recipient: '新收款方',
      amount: parseFloat(paymentForm.amount) || 0,
      type: 'outcome',
      status: '处理中'
    })
  }
  
  // 导航到交易记录页面
  const navigateToTransactions = () => {
    router.push('/transactions')
  }
  
  // 导航到账单页面
  const navigateToBilling = () => {
    router.push('/billing')
  }
  
  // 格式化货币
  const formatCurrency = (value: number) => {
    return value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
  }
  
  // 获取状态标签类型
  const getStatusType = (status: string) => {
    switch (status) {
      case '已完成':
        return 'success'
      case '处理中':
        return 'warning'
      case '已取消':
        return 'info'
      case '失败':
        return 'danger'
      default:
        return ''
    }
  }
  
  // 组件挂载时初始化图表
  onMounted(() => {
    setTimeout(() => {
      initCharts()
    }, 100)
    
    // 设置图表容器引用
    incomeChartRef.value = document.querySelector('.chart-section .el-col:first-child .chart-container > div')
    typeChartRef.value = document.querySelector('.chart-section .el-col:last-child .chart-container > div')
  })
  
  // 组件卸载时销毁图表
  onUnmounted(() => {
    if (incomeChart) {
      incomeChart.dispose()
    }
    if (typeChart) {
      typeChart.dispose()
    }
  })
  
  // 窗口大小改变时重绘图表
  window.addEventListener('resize', () => {
    if (incomeChart) {
      incomeChart.resize()
    }
    if (typeChart) {
      typeChart.resize()
    }
  })
  </script>
  
  <style lang="scss" scoped>
  .homepage-container {
    .overview-section {
      margin-bottom: 20px;
      
      .stat-card {
        border-radius: 8px;
        margin-bottom: 20px;
        
        .card-content {
          display: flex;
          align-items: center;
          
          .icon-container {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 60px;
            height: 60px;
            border-radius: 8px;
            margin-right: 16px;
            
            .el-icon {
              font-size: 28px;
              color: white;
            }
            
            &.bg-blue {
              background: linear-gradient(135deg, #409EFF, #64b5ff);
            }
            
            &.bg-green {
              background: linear-gradient(135deg, #67C23A, #85ce61);
            }
            
            &.bg-orange {
              background: linear-gradient(135deg, #E6A23C, #ebb563);
            }
            
            &.bg-purple {
              background: linear-gradient(135deg, #8e44ad, #9b59b6);
            }
          }
          
          .card-info {
            flex: 1;
            
            .card-title {
              font-size: 14px;
              color: #909399;
              margin-bottom: 8px;
            }
            
            .card-value {
              font-size: 24px;
              font-weight: bold;
              color: #303133;
            }
          }
        }
      }
    }
    
    .action-section {
      margin-bottom: 20px;
      
      .action-card {
        border-radius: 8px;
        margin-bottom: 20px;
        
        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
        
        .quick-actions {
          display: flex;
          flex-wrap: wrap;
          gap: 16px;
          
          .action-button {
            flex: 1;
            min-width: 120px;
            height: 80px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            
            .el-icon {
              font-size: 28px;
              margin-bottom: 8px;
            }
          }
        }
        
        .security-status {
          position: relative;
          min-height: 220px;
          
          .security-button {
            position: absolute;
            right: 10px;
            bottom: 10px;
          }
        }
      }
    }
    
    .transaction-section {
      margin-bottom: 20px;
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .income-amount {
        color: #67C23A;
        font-weight: bold;
      }
      
      .outcome-amount {
        color: #F56C6C;
        font-weight: bold;
      }
    }
    
    .chart-section {
      .chart-container {
        width: 100%;
      }
    }
  }
  
  :deep(.el-card) {
    border-radius: 8px;
    border: none;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .el-card__header {
      padding: 16px 20px;
      border-bottom: 1px solid #ebeef5;
      background-color: #fafafa;
    }
    
    .el-card__body {
      padding: 20px;
    }
  }
  
  :deep(.el-table) {
    border-radius: 8px;
    
    th {
      background-color: #f5f7fa;
    }
  }
  </style>